package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Board;
import com.example.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "板块接口")
@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {
    //从配置文件中读取,如果没有配置,默认是9
    @Value("${begin-forum.index.board-num}")
    private Integer indexBoardNum;
    @Autowired
    private IBoardService boardService;
    /**
     * 查询首页板块列表
     */
    @ApiOperation("获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList(){
        log.info("配置首页板块个数为: {}",indexBoardNum);
        //调用
        List<Board> boardList = boardService.selectByNum(indexBoardNum);
        //判断为空
        if(null==boardList){
            boardList = new ArrayList<>();
        }
        return AppResult.success(boardList);
    }

    @ApiOperation("获取对应板块信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@ApiParam("板块id") @RequestParam("id") @NonNull Long id){
        //直接调用, @NonNull 已经检测过是否为空
        Board board = boardService.selectById(id);
        if(null==board || board.getState() == 1){
            log.warn("当前选择板块不存在! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXIST));
        }
        return AppResult.success(board);
    }
}
